from rest_framework import permissions


class MobileClientPermission(permissions.BasePermission):
    ''' for mobile login person '''

    def has_permission(self, request, view):
        if request.method not in permissions.SAFE_METHODS:
            if request.user.has_perm('prj002.prj002_patient'):
                return True
            else:
                return False


class DiffRolePermisssion(permissions.BasePermission):
    """
    :不同角色不同操作权限
    1. 用户必须存在prj002开头的权限才能进行访问数据
    2. 信息只可以所有者修改
    3. 审核通过 => 则该信息所有人无法修改
    4. 已提交 => 无法修改
    """

    def has_permission(self, request, view):
        all_perm = request.user.get_all_permissions()

        own_perm = [perm for perm in all_perm if perm.startswith('prj002')]

        if not own_perm:
            return False

        return True

    def has_object_permission(self, request, view, obj):
        if hasattr(obj, 'info'):
            obj = obj.info

        if request.method in permissions.SAFE_METHODS:
            return True
        else:
            if hasattr(obj, 'check_status'):
                if obj.check_status in ('审核通过', '已提交'):
                    return False

            return obj.owner == request.user
